//
//  TYLevelPairs.m
//  VoiceMemoDemo
//
//  Created by 马天野 on 2018/8/5.
//  Copyright © 2018年 kangarootec. All rights reserved.
//

#import "TYLevelPairs.h"
#import <sys/utsname.h>

@implementation TYLevelPairs

+ (TYLevelPairs *)levelsWithLevel:(float)linearLevel peakLevel:(float)peakLevel avgPower:(float)avg peakPower:(float)peak{
    TYLevelPairs *levelPairs = [[TYLevelPairs alloc] init];
    levelPairs.avgPower = [TYLevelPairs returnPower:avg withBoolAvg:YES];
    levelPairs.peakPower = [TYLevelPairs returnPower:peak withBoolAvg:NO];
    levelPairs.linearLevel = linearLevel;
    levelPairs.linearPeakLevel = peakLevel;
    return levelPairs;
}

+ (float)returnAVGPower: (float)power {
    power = power + 160  - 40;
    double dB = 0;
    if (power < 0.f) {
        dB = 0;
    } else if (power < 40.f) {
        dB = (int)(power * 0.875);
    } else if (power < 100.f) {
        dB = (int)(power - 15);
    } else if (power < 110.f) {
        dB = (int)(power * 2.5 - 165);
    } else {
        dB = 110;
    }
    return dB;
}

+ (float)returnPower: (float)power withBoolAvg:(BOOL)isAvg{
    
//    float minValue = -60;
//        //把60作为获取分配的范围
//        float range = 60;
//        //把100作为输出分贝范围
//        float outRange = 100;
//        //确保在最小值范围内
//        if (power < minValue){
//            power = minValue;
//        }
//        //计算显示分贝
//        float decibels = (power + range) / range * outRange;
//        NSLog(@"==========%f",  decibels);
//    return decibels;
    
    power = power + 160  - 50;
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *phoneType = [[[[NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding] componentsSeparatedByString:@","] firstObject] stringByReplacingOccurrencesOfString:@"iPhone" withString:@""];
    if ([phoneType integerValue] < 8 && isAvg) {
        power = power + 10;
    }
    int dB = 0;
    if (power < 0.f) {
        dB = 0;
    } else if (power < 40.f) {
        dB = (int)(power * 0.725);
    }
    else if (power < 60.f) {
        dB = (int)(power * 0.625);
    }
    else if (power < 80.f) {
        dB = (int)(power * 0.525);
    }
    else if (power < 90.f) {
        dB = (int)(power * 0.725);
    }
    else if (power < 100.f) {
        dB = (int)(power - 25);
    }
    else if (power < 110.f) {
        dB = (int)(power - 15);
    }
//    else if (power < 110.f) {
//        dB = (int)(power * 2.5 - 165);
//    }
//    else {
//        dB = 110;
//    }
    else {
        dB = 100;
    }
    return dB;
}

@end
